package gatewayapi

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"fmt"

	context "context"

	k8gbv1beta1 "github.com/k8gb-io/k8gb/api/v1beta1"
	"github.com/k8gb-io/k8gb/controllers/logging"
	"github.com/k8gb-io/k8gb/controllers/utils"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"
	gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1"
)

var log = logging.Logger()

// GetGateway retrieves the gateway referenced by a route resource
func GetGateway(route RouteSpec, k8sClient client.Client) (*gatewayapiv1.Gateway, error) {
	var gateways []types.NamespacedName
	for _, parentRef := range route.GetParentRefs() {
		if parentRef.Kind != nil && string(*parentRef.Kind) != "Gateway" {
			log.Warn().
				Str("route", route.GetName()).
				Str("namespace", route.GetNamespace()).
				Str("parentRef", string(parentRef.Name)).
				Msgf("Only Gateway parent references are supported, got %s", string(*parentRef.Kind))
			continue
		}

		namespace := route.GetNamespace()
		if parentRef.Namespace != nil {
			namespace = string(*parentRef.Namespace)
		}
		gateways = append(gateways, types.NamespacedName{
			Namespace: namespace,
			Name:      string(parentRef.Name),
		})
	}

	if len(gateways) != 1 {
		return nil, fmt.Errorf("expected exactly 1 Gateway to be referenced by the route but %d were found", len(gateways))
	}

	gateway := &gatewayapiv1.Gateway{}
	err := k8sClient.Get(context.TODO(), gateways[0], gateway)
	if err != nil {
		if errors.IsNotFound(err) {
			log.Info().
				Str("gateway", gateways[0].Name).
				Str("namespace", gateways[0].Namespace).
				Msg("Can't find Gateway resource referenced by route")
		}
		return nil, err
	}
	return gateway, nil
}

// GetServersFromRoute retrieves the GSLB server configuration from a route resource
func GetServersFromRoute(route RouteSpec) ([]*k8gbv1beta1.Server, error) {
	hostnames := route.GetHostnames()
	if len(hostnames) < 1 {
		return nil, fmt.Errorf("can't find hosts in route %s", route.GetName())
	}

	servers := []*k8gbv1beta1.Server{}
	for _, hostname := range hostnames {
		server := &k8gbv1beta1.Server{
			Host:     string(hostname),
			Services: []*k8gbv1beta1.NamespacedName{},
		}
		for _, rule := range route.GetRules() {
			for _, backendRef := range rule.GetBackendRefs() {
				namespace := route.GetNamespace()
				if backendRef.Namespace != nil {
					namespace = string(*backendRef.Namespace)
				}
				server.Services = append(server.Services, &k8gbv1beta1.NamespacedName{
					Name:      string(backendRef.Name),
					Namespace: namespace,
				})
			}
		}
		servers = append(servers, server)
	}
	return servers, nil
}

// GetGslbExposedIPs retrieves the load balancer IP address of the GSLB
func GetGslbExposedIPs(gateway *gatewayapiv1.Gateway, gslbAnnotations map[string]string, parentZoneDNSServers utils.DNSList) ([]string, error) {
	// fetch the IP addresses of the reverse proxy from an annotation if it exists
	if ingressIPsFromAnnotation, ok := gslbAnnotations[utils.ExternalIPsAnnotation]; ok {
		return utils.ParseIPAddresses(ingressIPsFromAnnotation)
	}

	// if there is no annotation -> fetch the IP addresses from the Status of the Gateway resource
	gslbIngressIPs := []string{}
	for _, address := range gateway.Status.Addresses {
		switch {
		case address.Type == nil, *address.Type == gatewayapiv1.AddressType("IPAddress"):
			gslbIngressIPs = append(gslbIngressIPs, address.Value)
		case *address.Type == gatewayapiv1.AddressType("Hostname"):
			IPs, err := utils.Dig(address.Value, 8, parentZoneDNSServers...)
			if err != nil {
				log.Warn().Err(err).Msg("Dig error resolving Gateway API Gateways's hostname")
				return nil, err
			}
			gslbIngressIPs = append(gslbIngressIPs, IPs...)
		default:
			log.Warn().
				Str("gateway", gateway.Name).
				Str("namespace", gateway.Namespace).
				Str("address", address.Value).
				Msg("Unsupported address type")
			return nil, fmt.Errorf("unsupported address type %s", *address.Type)
		}
	}

	return gslbIngressIPs, nil
}
